package api

import (
	"cs/models"
	"cs/request"
	"cs/util"
	"cs/ws"
	"errors"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func GetConversationInfo(c *gin.Context) {
	guest_id := c.Query("guest_id")
	conversation, err := models.GetConversationInfo(guest_id)
	if err == nil {
		c.JSON(http.StatusOK, gin.H{"status": "success", "conversation": conversation})
	} else {
		c.JSON(http.StatusOK, gin.H{"status": "failed", "message": err.Error()})
	}
}

func MarkAsVip(c *gin.Context) {
	guest_id, _ := strconv.Atoi(c.Param("guest_id"))
	err := models.MarkGuestAsVip(guest_id)
	if err == nil {
		c.JSON(http.StatusOK, gin.H{"status": "success", "message": "ok"})
	} else {
		c.JSON(http.StatusOK, gin.H{"status": "failed", "message": err.Error()})
	}
}

func GuestLogin(c *gin.Context) {
	var form request.AddGuestForm
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数验证失败"})
		return
	}

	guest, err := models.GetGuestByUid(form.Uid)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		ip := c.ClientIP()
		newGuest := models.Guest{
			Name: form.Name,
			Uid:  form.Uid,
			IP:   ip,
			City: util.ParseIp(ip),
		}
		models.AddGuest(newGuest)

		c.JSON(http.StatusOK, gin.H{"status": "success", "data": newGuest})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{"status": "success", "data": guest})
	}
}

func IsOnline(c *gin.Context) {
	guest_id, _ := strconv.Atoi(c.Param("guest_id"))
	online := ws.IsOnline(guest_id, "guest")
	if online {
		c.JSON(http.StatusOK, gin.H{"status": "success", "data": 1})
	} else {
		c.JSON(http.StatusOK, gin.H{"status": "success", "data": 0})
	}
}
